/*
 Xern Entity Relocation Network
 Copyright (C) 2010-2011 Ronie Salgado <roniesalg@gmail.com>

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

#include <stdio.h>
#include "Xern/Exceptions.hpp"
#include "Xern/FileSystem.hpp"
#include "Xern/Log.hpp"
#include "Xern/PluginRegistry.hpp"
#include "Xern/Plugin.hpp"

namespace Xern
{
	typedef void (*PluginEntry) ();

	PluginRegistry::PluginRegistry()
	{
	}

	PluginRegistry::~PluginRegistry()
	{
	}

	void PluginRegistry::LoadPlugins()
	{
		// Read the elements of the plugins directory.
		DirectoryElements files;
		ReadDirectory("plugins", files);

		for(size_t i = 0; i < files.size(); i++)
		{
			std::string path = "plugins/" + files[i];

			// Check that it is actually a file.
			if(!IsFile(path))
				continue;

			// Try to load the plugin.
			try
			{
				// Load the plugin.
				boost::shared_ptr<PluginModule> module(new PluginModule());
				module->Load(path);

				// Store the module.
				modules.push_back(module);

				// Find the optional LoadPlugin() function
				PluginEntry LoadPlugin =
					(PluginEntry)module->GetProcedure("LoadPlugin");

				if(LoadPlugin) // Load the plugin.
					LoadPlugin();

				LogConsole->Notify("Loaded plugin module '%s'", files[i].c_str());
			}
			catch(XernException &e)
			{
				LogConsole->Error("%s", e.what());
			}
		}
	}

	void PluginRegistry::UnloadPlugins()
	{
		for(size_t i = 0; i < modules.size(); i++)
		{
			boost::shared_ptr<PluginModule> module = modules[i];

			// Find the UnloadPlugin procedure.
			PluginEntry UnloadPlugin =
					(PluginEntry)module->GetProcedure("UnloadPlugin");

			// Unload the plugin.
			if(UnloadPlugin)
				UnloadPlugin();

			// Unload the module.
			module->Unload();
		}

		// Clear the modules.
		modules.clear();
	}

	void PluginRegistry::Register(const std::string &group, const std::string &name,
			boost::shared_ptr<IInterface> interface)
	{
		// Create the group.
		PluginGroup &g = CreateGroup(group);

		// Insert the interface into the group.
		g.insert(std::make_pair(name, interface));
	}

	void PluginRegistry::Unregister(const std::string &group, const std::string &name)
	{
		// Find the group.
		groupsType::iterator it = groups.find(group);
		if(it != groups.end())
			it->second.erase(name);
	}

	boost::shared_ptr<IInterface>
	PluginRegistry::FindPlugin(const std::string &group, const std::string &name) const
	{
		// Find the group.
		groupsType::const_iterator it = groups.find(group);
		if(it != groups.end())
		{
			const PluginGroup &group = it->second;

			// Find the interface.
			PluginGroup::const_iterator it2 = group.find(name);
			if(it2 != group.end())
				return it2->second;
		}
		return boost::shared_ptr<IInterface> ();
	}

	PluginGroup &PluginRegistry::CreateGroup(const std::string &name)
	{
		// Find an existent group.
		groupsType::iterator it = groups.find(name);
		if(it != groups.end())
			return it->second;

		// Create the group.
		groups[name] = PluginGroup();

		// Return the group.
		return groups[name];
	}

	const PluginGroup *PluginRegistry::QueryGroup(const std::string &group) const
	{
		groupsType::const_iterator it = groups.find(group);
		if(it != groups.end())
			return &it->second;
		return NULL;
	}

}; // namespace Xern
